<template>
  <div class="search-result">
    <van-list 
      v-model="loading" 
      :finished="finished" 
      :error="error"
      error-text="加载失败，请点击重试"
      finished-text="没有更多了" 
      @load="onLoad">
      <van-cell v-for="(article, index) in list" :key="index" :title="article.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/serach.js'
export default {
  name: 'searchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      per_page: 20,
      error: false,
    }
  },
  methods: {
    async onLoad () {
      try {
        // 启动端口获取搜索数据
        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.per_page,
          q: this.searchText,
        })
        const { results } = data.data
        // 把数据推送到list里面
        this.list.push(...results)
        // 设置加载状态结束
        this.loading = false

        // 判断是否加载完毕
        if (results.length){
          this.page++
        } else {
          this.finished = true
        }
      } catch (error) {
        // this.$toast('获取数据失败,请稍后重试')
        // 展示加载失败的提示状态
        this.error = true
        // 加载失败了. loading 也要关闭
        this.loading = false
      }
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.list.push(this.list.length + 1)
        }

        // 加载状态结束
        this.loading = false

        // 数据全部加载完成
        if (this.list.length >= 40) {
          this.finished = true
        }
      }, 1000)
    }
  },
}
</script>

<style lang="less" scoped>
</style>
